//
//  JKPurchaseVC.m
//  JackToolsBox
//
//  Created by Blue on 2020/1/19.
//  Copyright © 2020 Jack Xue. All rights reserved.
//

#import "JKPurchaseVC.h"
#import "JKPurchaseView.h"
#import "ECPurchase.h"
#import "BSAnimationView.h"
#import "JkReceiptManager.h"

#define K_PRODUCT_1M        @"com.wanshan.xssc.1m"
#define K_PRODUCT_1M_SUB    @"com.wanshan.xssc.1m.subscription"

@interface JKPurchaseVC ()<ECPurchaseTransactionDelegate>

@end

@implementation JKPurchaseVC

- (void)loadView
{
    [super loadView];
    
    JKPurchaseView *view = [[JKPurchaseView alloc] initWithFrame:self.view.bounds];
    view.delegate = self;
    self.view = view;
    view = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[ECPurchase shared] setTransactionDelegate:self];
    [[ECPurchase shared] setVerifyRecepitMode:ECVerifyRecepitModeCustomServer];
    
    
    
}

#pragma mark - action
- (void)buy
{
    [[ECPurchase shared]addPayment:K_PRODUCT_1M];
    [BSAnimationView animationWithMessage:@"支付中..." inView:self.navigationController.view withDim:YES isOnlyText:NO withDuration:0];
}

- (void)restorePurchase
{
    [[ECPurchase shared] restoreCompletedPayment];
    [BSAnimationView animationWithMessage:@"恢复中..." inView:self.navigationController.view withDim:YES isOnlyText:NO withDuration:0];
}

- (void)allRestoreProducts
{
    NSMutableArray *trans = [[ECPurchase shared] getRestoreTrans];
    NSLog(@"...");
}

#pragma mark - 完成购买
- (void)didCompleteTransaction:(NSString *)proIdentifier withReceipt:(NSString *)receipt
{
    /*
     --开始生成订单
     model - self进行管理 @{proIdentifier:model}
     --回调，完成订单 -- 直接上传我方服务器
     --我方服务器验证
     proIdentifier 在 self中取orderId,sub
        orderId存在 && sub == yes ->普通验证接口
        else 订阅验证接口
     如果失败则记录proIdentifier，orderId，sub，receipt
     --验证成功回调
     proIdentifier - 结束本地待验证队列
     */
    [BSAnimationView stopAnimation];
    

}

#pragma mark - 交易失败
- (void)didFailedTransaction:(NSString *)proIdentifier error:(NSError *)error
{
    [BSAnimationView stopAnimation];
    if (error) {
        if (error.code == SKErrorPaymentNotAllowed) {
            NSLog(@"Jk - 用户禁止购买");
        }else if (error.code == SKErrorPaymentCancelled){
            NSLog(@"Jk - 用户取消购买");
        }else if (error.code == SKErrorUnknown){
            NSLog(@"Jk - proudctUUID无效");
        }else if (error.code == SKErrorCloudServiceNetworkConnectionFailed){
            NSLog(@"Jk - 网络错误");
        }
    }
}

#pragma mark - 恢复购买
-(void)didRestoreTransaction:(NSString *)proIdentifier
{
    //成功恢复购买，等到成功完成一次验证后重置计数
    [BSAnimationView stopAnimation];
}

- (void)didFailedRestoreTransaction:(NSError *)error
{
    //恢复购买失败
    [BSAnimationView stopAnimation];
}






@end
